package com.houzhiwen.test;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class MyListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        String initParameter = servletContextEvent.getServletContext().getInitParameter("contextConfigLocation");
        //当服务器启动时 读取spring核心配置文件创建spring容器对象 并将其存入servletContext作用域中
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("initParameter");
        ServletContext servletContext = servletContextEvent.getServletContext();
        servletContext.setAttribute("spring",applicationContext);
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        //当服务器关闭时 获取作用域中spring容器对象 调用close方法关闭容器
        ServletContext servletContext = servletContextEvent.getServletContext();
        ClassPathXmlApplicationContext applicationContext= (ClassPathXmlApplicationContext) servletContext.getAttribute("spring");
        applicationContext.close();
    }
}
